package com.xjw.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.xjw.annotation.FXController;
import com.xjw.annotation.FXRedirect;
import com.xjw.annotation.FXWindow;
import com.xjw.coreutil.common.PropUtil;
import com.xjw.coreutil.http.JsonUtil;
import com.xjw.coreutil.http.Result;
import com.xjw.entity.FXBaseController;
import com.xjw.entity.WebSocketUser;
import com.xjw.utils.StringUtil;
import com.xjw.utils.ToolUtil;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author 徐军文
 * @since 2021/11/6 1:02
 */
@FXController(path = "fxml/init.fxml")
@FXWindow(mainStage = true, title = "注册界面", icon = "image/icon.png")
public class initController extends FXBaseController implements Initializable {

    PropUtil propUtil = PropUtil.getInstance(PropUtil.INITDATA);

    String url = "http://180.76.134.142:8080/infocollect/websocket/createUser?userName=";

    @FXML
    private TextField userNameEle;

    @FXML
    private Text msgEle;

    private Log log = LogFactory.get("init:");

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Boolean flag = propUtil.getBool("initFlag");
        if (Boolean.TRUE.equals(flag)) {
            ToolUtil.execAsync(this::toGoBang);
        }
    }

    @FXRedirect
    public String toGoBang() {
        return "ChessController";
    }

    @FXML
    private void createUser() {
        String userName = userNameEle.getText();
        if (StringUtil.isEmpty(userName)) {
            setMsg("昵称不可为空");
        }
        String res = HttpRequest.get(url + userName).execute().body();
        log.info(res);
        Result result = Result.asyResult(res);
        if (result.getSucFlag()) {
            ToolUtil.execAsync(()->{
                WebSocketUser user = JsonUtil.parseObject(result.getData().toString(), WebSocketUser.class);
                propUtil.setProperty("initFlag", true);
                propUtil.putJson("userInfo", user);
                toGoBang();
            });
        } else {
            setMsg(result.getErrorMsg());
        }
    }

    private void setMsg(String msg) {
        ToolUtil.setMsg(msgEle, msg);
    }

}
